package com.zz.rabbitmq.topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.zz.rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        // 2.设置参数
        factory.setHost(Constants.IP);
        factory.setPort(Constants.PORT);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        Connection connection = factory.newConnection();
        // 3.创建 channel
        Channel channel = connection.createChannel();
        // 4.声明队列
        channel.queueDeclare(Constants.TOPIC_QUEUE1, true, false, false, null);
        channel.queueDeclare(Constants.TOPIC_QUEUE2, true, false, false, null);
        // 5 声明交换机
        channel.exchangeDeclare(Constants.TOPIC_EXCHANGE, "topic");
        // 6.绑定队列到交换机
        channel.queueBind(Constants.TOPIC_QUEUE1, Constants.TOPIC_EXCHANGE, "*.a.*");
        channel.queueBind(Constants.TOPIC_QUEUE2, Constants.TOPIC_EXCHANGE, "*.*.b");
        channel.queueBind(Constants.TOPIC_QUEUE2, Constants.TOPIC_EXCHANGE, "c.#");
        // 7.发送消息
        String message = "Hello topic, ae.a.f!";
        // 只发送到队列1
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "ae.a.f", null, message.getBytes());
        String message2 = "Hello fanout, ef.a.b!";
        // 发送到队列1和队列2
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "ef.a.b", null, message.getBytes());
        String message3 = "Hello fanout, c.ef.d!";
        // 发送到队列2
        channel.basicPublish(Constants.TOPIC_EXCHANGE, "c.ef.d", null, message.getBytes());
        System.out.println("消息发送成功");
        // 8.关闭 channel
        channel.close();
        // 9.关闭连接
        connection.close();
    }
}
